package name;

import java.io.*;
import java.net.Socket;

public class ServerReadThread  extends  Thread {
    private Socket socket;
    //创造一个socket有参构造器
    public ServerReadThread(Socket socket){
        this.socket=socket;

    }

    @Override
    public void run() {
        final DataInputStream dip;
        try {
            InputStream in = socket.getInputStream();
            dip = new DataInputStream(in);
            while (true) {
                try {
                    String s = dip.readUTF();
                    System.out.println(s);
                    sendmag(s);
                } catch (IOException e) {
                    System.out.println("客户端已经下线");
                    System.out.println(socket.getRemoteSocketAddress());
                    ChatSever.oneline.remove(socket);
                    dip.close();
                    socket.close();
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

    private void sendmag(String s) throws IOException {
        for (Socket socket1 : ChatSever.oneline) {

             OutputStream outputStream = socket1.getOutputStream();
             DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
             dataOutputStream.writeUTF(s);

        }
    }
}
